<template>
  <div class="history-page">
    <div class="content-wrapper">
      <div class="header">
        <h2 class="title">浏览历史</h2>
        <div class="header-actions">
          <el-button
            type="danger"
            size="small"
            :disabled="selectedHistoryItems.length === 0"
            @click="handleBatchDelete"
            :loading="isLoading"
            class="delete-batch-btn"
          >
            <i class="el-icon-delete"></i> 批量删除
          </el-button>
        </div>
      </div>

      <div class="list-content">
        <div class="table-header">
          <el-checkbox
            :model-value="isAllSelected"
            :indeterminate="isIndeterminate"
            @change="handleSelectAll"
          >
            全选
          </el-checkbox>
        </div>

        <div
          class="history-item"
          v-for="item in historyData"
          :key="item.id"
          :class="{
            pulse: item.isNew,
            selected: selectedHistoryItems.includes(item.id),
          }"
        >
          <div class="item-select">
            <el-checkbox 
              :value="selectedHistoryItems.includes(item.id)"
              @change="(val) => handleSelectItem(val, item.id)"
            ></el-checkbox>
          </div>

          <img :src="item.cover" class="activity-img" />

          <div class="activity-info">
            <div class="top">
              <h3 class="activity-title">{{ item.activityTitle }}</h3>
              <span class="view-time">
                <i class="el-icon-time"></i>
                浏览时间：{{ item.viewedTime }}
              </span>
            </div>
            <p class="activity-description">{{ item.description }}</p>
            <div class="meta">
              <span class="meta-item category">
                <i class="el-icon-collection-tag"></i>
                {{ item.categoryName }}
              </span>
              <span class="meta-item time">
                <i class="el-icon-date"></i>
                {{ item.startTime }} - {{ item.endTime }}
              </span>
              <span class="meta-item location">
                <i class="el-icon-location"></i>
                {{ item.detailAddress }}
              </span>
            </div>
          </div>

          <div class="action-buttons">
            <el-button
              type="primary"
              class="detail-btn"
              @click="navigateToActivity(item.activityId)"
            >
              查看详情
              <i class="el-icon-arrow-right"></i>
            </el-button>

            <el-button
              type="danger"
              class="delete-btn"
              @click="handleDelete(item.id)"
              :loading="isLoading"
            >
              <i class="el-icon-delete"></i>
              删除
            </el-button>
          </div>
        </div>

        <div class="empty-state" v-if="historyData.length === 0">
          <i class="el-icon-document"></i>
          <p>暂无浏览记录</p>
          <el-button type="primary" @click="$router.push('/index')">浏览活动</el-button>
        </div>
      </div>

      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          :page-size="pagination.size"
          :current-page="pagination.page"
          @current-change="onPageChange"
          @size-change="onSizeChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import {
  activityHistoryPage,
  activityHistoryDeleteById,
  activityHistoryDeleteBatch,
} from "@/apis/user/activity-history";
import { ElMessage, ElMessageBox } from "element-plus";

const router = useRouter();
const historyData = ref([]);
const pagination = reactive({
  page: 1,
  size: 5,
  total: 0,
});
const selectedHistoryItems = ref([]);
const isLoading = ref(false);

// 搜索输入框搜索条件
const search = reactive({
  userId: "",
});

// 过滤对应的条件
const filter = ref({});

// 存储排序字段
const orders = reactive({
  column: "viewedTime", // 改为按浏览时间排序
  isAsc: false,         // 默认最新浏览记录在前
});

const getHistoryPage = async () => {
  try {
    isLoading.value = true;
    const res = await activityHistoryPage(
      {
        filter: filter.value,
        search: search,
        orders: [orders],
      },
      pagination.page,
      pagination.size
    );

    historyData.value = res.data.records;
    pagination.total = res.data.total;
  } catch (error) {
    console.error("获取历史记录失败:", error);
    ElMessage.error("获取历史记录失败，请稍后重试");
  } finally {
    isLoading.value = false;
  }
};

const onPageChange = (page) => {
  pagination.page = page;
  getHistoryPage();
};

const onSizeChange = (size) => {
  pagination.size = size;
  pagination.page = 1; // 重置页码为1
  getHistoryPage();
};

const navigateToActivity = (activityId) => {
  router.push({
    name: "activityDetail",
    params: { activityId },
  });
};

// 选择单个项目
const handleSelectItem = (val, itemId) => {
  if (val) {
    selectedHistoryItems.value.push(itemId);
  } else {
    const index = selectedHistoryItems.value.indexOf(itemId);
    if (index !== -1) {
      selectedHistoryItems.value.splice(index, 1);
    }
  }
};

// 删除单条浏览记录
const handleDelete = async (historyId) => {
  try {
    await ElMessageBox.confirm("确定要删除这条浏览记录吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    isLoading.value = true;
    const res = await activityHistoryDeleteById(historyId);
    if (res.code === "00000") {
      ElMessage.success("删除成功");
      getHistoryPage(); // 重新加载数据
    } else {
      ElMessage.error(res.message || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除浏览记录失败:", error);
      ElMessage.error("删除失败，请稍后重试");
    }
  } finally {
    isLoading.value = false;
  }
};

// 批量删除浏览记录
const handleBatchDelete = async () => {
  if (selectedHistoryItems.value.length === 0) {
    ElMessage.warning("请先选择要删除的记录");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedHistoryItems.value.length} 条浏览记录吗？`,
      "批量删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    isLoading.value = true;
    const res = await activityHistoryDeleteBatch(selectedHistoryItems.value);
    if (res.code === "00000") {
      ElMessage.success("批量删除成功");
      selectedHistoryItems.value = []; // 清空选中项
      getHistoryPage(); // 重新加载数据
    } else {
      ElMessage.error(res.message || "批量删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("批量删除浏览记录失败:", error);
      ElMessage.error("批量删除失败，请稍后重试");
    }
  } finally {
    isLoading.value = false;
  }
};

// 全选/取消全选
const handleSelectAll = (val) => {
  if (val) {
    // 全选 - 获取所有记录的ID
    selectedHistoryItems.value = historyData.value.map((item) => item.id);
  } else {
    // 取消全选
    selectedHistoryItems.value = [];
  }
};

// 计算全选状态
const isAllSelected = computed(() => {
  return (
    historyData.value.length > 0 &&
    selectedHistoryItems.value.length === historyData.value.length
  );
});

// 计算部分选中状态
const isIndeterminate = computed(() => {
  return (
    selectedHistoryItems.value.length > 0 &&
    selectedHistoryItems.value.length < historyData.value.length
  );
});

onMounted(() => {
  getHistoryPage();
});
</script>

<style scoped>
.history-page {
  padding: 24px;
  background-color: #f8fafc;
  min-height: calc(100vh - 120px);
  position: relative;
}

.content-wrapper {
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header .title {
  font-size: 28px;
  font-weight: 700;
  color: #1e293b;
  position: relative;
  padding-left: 16px;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.header .title::before {
  content: "";
  position: absolute;
  left: 0;
  top: 15%;
  height: 70%;
  width: 6px;
  background: linear-gradient(to bottom, #6366f1, #8b5cf6);
  border-radius: 3px;
}

.delete-batch-btn {
  background-color: #f43f5e;
  border-color: #f43f5e;
  font-weight: 500;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.delete-batch-btn:hover {
  background-color: #e11d48;
  border-color: #e11d48;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(225, 29, 72, 0.3);
}

.delete-batch-btn:disabled {
  background-color: #fda4af;
  border-color: #fda4af;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.list-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 24px;
}

.table-header {
  display: flex;
  padding: 16px 24px;
  background: #fff;
  border-radius: 16px 16px 0 0;
  margin-bottom: 4px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  border-bottom: 1px solid #f1f5f9;
}

.history-item {
  display: flex;
  align-items: flex-start;
  background: #fff;
  padding: 24px;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
  border-left: 4px solid transparent;
  position: relative;
  overflow: hidden;
}

.history-item::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(to right, rgba(99, 102, 241, 0.05), transparent);
  opacity: 0;
  transition: opacity 0.3s ease;
  pointer-events: none;
}

.history-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
  border-left: 4px solid #6366f1;
}

.history-item:hover::after {
  opacity: 1;
}

.history-item.selected {
  background-color: rgba(99, 102, 241, 0.05);
  border-left: 4px solid #6366f1;
}

.item-select {
  margin-right: 20px;
  display: flex;
  align-items: center;
  height: 110px;
}

.pulse {
  animation: pulse 2s infinite;
  position: relative;
}

.pulse::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(99, 102, 241, 0.1);
  border-radius: 16px;
  z-index: -1;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(99, 102, 241, 0.6);
  }
  70% {
    box-shadow: 0 0 0 15px rgba(99, 102, 241, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(99, 102, 241, 0);
  }
}

.activity-img {
  width: 160px;
  height: 120px;
  object-fit: cover;
  border-radius: 12px;
  margin-right: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.history-item:hover .activity-img {
  transform: scale(1.05) rotate(1deg);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
}

.activity-info {
  flex: 1;
  padding-right: 16px;
}

.top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.activity-title {
  font-size: 20px;
  font-weight: 700;
  color: #1e293b;
  margin: 0;
  line-height: 1.4;
  transition: color 0.3s ease;
}

.history-item:hover .activity-title {
  color: #4f46e5;
}

.view-time {
  font-size: 14px;
  color: #64748b;
  display: flex;
  align-items: center;
  background-color: #f8fafc;
  padding: 6px 12px;
  border-radius: 20px;
  white-space: nowrap;
}

.view-time i {
  margin-right: 6px;
  color: #6366f1;
}

.activity-description {
  margin: 12px 0;
  color: #475569;
  line-height: 1.7;
  font-size: 15px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.meta {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-top: 16px;
}

.meta-item {
  font-size: 14px;
  color: #64748b;
  display: flex;
  align-items: center;
  padding: 6px 12px;
  border-radius: 20px;
  background-color: #f8fafc;
  transition: all 0.3s ease;
}

.meta-item:hover {
  transform: translateY(-2px);
}

.meta-item i {
  margin-right: 6px;
  font-size: 16px;
}

.meta-item.category {
  color: #7c3aed;
  background-color: #f5f3ff;
}

.meta-item.category i {
  color: #8b5cf6;
}

.meta-item.time {
  color: #db2777;
  background-color: #fdf2f8;
}

.meta-item.time i {
  color: #ec4899;
}

.meta-item.location {
  color: #059669;
  background-color: #ecfdf5;
}

.meta-item.location i {
  color: #10b981;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-left: 16px;
}

.detail-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 10px 20px;
  font-weight: 600;
  transition: all 0.3s ease;
  background: linear-gradient(to right, #6366f1, #8b5cf6);
  border: none;
  border-radius: 10px;
  min-width: 120px;
}

.detail-btn:hover {
  transform: translateX(4px);
  box-shadow: 0 6px 20px rgba(99, 102, 241, 0.4);
  background: linear-gradient(to right, #4f46e5, #7c3aed);
}

.detail-btn i {
  transition: transform 0.3s ease;
}

.detail-btn:hover i {
  transform: translateX(4px);
}

.delete-btn {
  padding: 10px 0;
  transition: all 0.3s ease;
  border: 1px solid #fee2e2;
  background-color: #fee2e2;
  color: #ef4444;
  border-radius: 10px;
  font-weight: 500;
  min-width: 120px;
}

.delete-btn:hover {
  background-color: #ef4444;
  border-color: #ef4444;
  color: white;
  box-shadow: 0 6px 20px rgba(239, 68, 68, 0.3);
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 0;
  color: #64748b;
  background-color: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.04);
}

.empty-state i {
  font-size: 64px;
  margin-bottom: 20px;
  color: #cbd5e1;
}

.empty-state p {
  font-size: 18px;
  margin-bottom: 24px;
}

.empty-state button {
  padding: 12px 24px;
  background: linear-gradient(to right, #6366f1, #8b5cf6);
  border: none;
  border-radius: 10px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.empty-state button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(99, 102, 241, 0.4);
}

/* 分页容器样式修改 */
.pagination-container {
  display: flex;
  justify-content: center;
  padding: 24px 0;
  margin-top: 20px;
  background-color: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.04);
}

/* 响应式设计 */
@media screen and (max-width: 1024px) {
  .history-item {
    flex-direction: column;
    padding: 20px;
  }
  
  .activity-img {
    width: 100%;
    height: 200px;
    margin-right: 0;
    margin-bottom: 16px;
  }
  
  .item-select {
    position: absolute;
    top: 20px;
    left: 20px;
    z-index: 10;
    height: auto;
    margin-right: 0;
  }
  
  .item-select .el-checkbox {
    background-color: rgba(255, 255, 255, 0.8);
    border-radius: 50%;
    padding: 8px;
  }
  
  .action-buttons {
    flex-direction: row;
    margin-left: 0;
    margin-top: 16px;
    width: 100%;
  }
  
  .detail-btn, .delete-btn {
    flex: 1;
  }
  
  .top {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .view-time {
    margin-top: 8px;
  }
}

@media screen and (max-width: 640px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .header-actions {
    width: 100%;
  }
  
  .delete-batch-btn {
    width: 100%;
  }
  
  .meta {
    flex-direction: column;
    gap: 8px;
  }
  
  .meta-item {
    width: 100%;
  }
}
</style>